//
//  LogoutViewController.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/5/27.
//

#import "LogoutViewController.h"
#import "YMCountDown.h"
#import "CountDownBtn.h"
#import "SendSmsCodeManager.h"
#import "DeleteUserManager.h"


@interface LogoutViewController ()<UITextFieldDelegate,YMCountDownDelegate,NoDoubleButtonDelegate,JPAPIManagerCallBackDelegate>

@property(nonatomic,strong)UILabel *phoneTipLabel;
@property(nonatomic,strong)UITextField *codeTF;
@property(nonatomic,strong)CountDownBtn *countDownBtn;
@property(nonatomic,strong)YMCountDown *countDown;
@property(nonatomic,strong)SendSmsCodeManager *sendCodeManager;
@property(nonatomic,strong)DeleteUserManager *deleteUserManager;
@property(nonatomic,strong)UIView *bgView;

@end

@implementation LogoutViewController

-(SendSmsCodeManager *)sendCodeManager{
    if(!_sendCodeManager){
        _sendCodeManager = [[SendSmsCodeManager alloc]init];
        _sendCodeManager.delegate = self;
    }
    return _sendCodeManager;
}

-(DeleteUserManager *)deleteUserManager{
    if(!_deleteUserManager){
        _deleteUserManager = [[DeleteUserManager alloc]init];
        _deleteUserManager.delegate = self;
    }
    return _deleteUserManager;
}

-(void)viewDidLoad{
    [super viewDidLoad];
    [self createUI];
}

-(void)createUI{
    
    [self.customNavigationBar setTitle:@"注销申请"];
    
    UIView *topBgView = [[UIView alloc]init];
    topBgView.backgroundColor = UIColorHex_(0xFF781D,0.1);
    [self.view addSubview:topBgView];
    [topBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(@0);
        make.top.mas_equalTo(kYM_NAVIGATIONBAR_HEIGHT);
        make.height.mas_equalTo(@56);
    }];
    UILabel *tipLabel = [[UILabel alloc]init];
    tipLabel.font = JPUIFontPingFangSCRegular(13);
    tipLabel.textColor = UIColorHex(0xFF781D);
    tipLabel.numberOfLines = 2;
    tipLabel.text = @"账号注销后，您无法正常登录APP，对应的相关权益将同时作废，望须知！";
    [topBgView addSubview:tipLabel];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@16);
        make.right.mas_equalTo(@-16);
        make.top.mas_equalTo(@10);
    }];
    
    UIView *bgView = [[UIView alloc]init];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.layer.cornerRadius = 10;
    bgView.layer.masksToBounds = YES;
    [self.view addSubview:bgView];
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@16);
        make.right.mas_equalTo(@-16);
        if(isIPAD){
            make.top.mas_equalTo(topBgView.mas_bottom).offset(20);
            make.height.mas_equalTo(@142);
        }else{
            make.top.mas_equalTo(topBgView.mas_bottom).offset(kWFit(20));
            make.height.mas_equalTo(kWFit(142));
        }
    }];
    self.bgView = bgView;
    
    
    UILabel *titleLabel = [[UILabel alloc]init];
    titleLabel.font = JPUIFontPingFangSCMedium(15);
    titleLabel.textColor = KFontBlackColor;
    titleLabel.text = @"请完成以下验证";
    [bgView addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@16);
        if(isIPAD){
            make.top.mas_equalTo(@16);
        }else{
            make.top.mas_equalTo(kWFit(16));
        }
        make.right.mas_equalTo(@-16);
    }];
    
    self.phoneTipLabel = [[UILabel alloc]init];
    self.phoneTipLabel.font = JPUIFontPingFangSCRegular(14);
    self.phoneTipLabel.textColor = KFontGrayColor;
    NSString *phone = [[NSUserDefaults standardUserDefaults]objectForKey:@"phone"];
    if(phone){
        self.phoneTipLabel.text = [NSString stringWithFormat:@"请输入%@收到的短信验证码",[self hideMiddleDigits:phone]];
    }
    [bgView addSubview:self.phoneTipLabel];
    [self.phoneTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@16);
        if(isIPAD){
            make.top.mas_equalTo(@41);
        }else{
            make.top.mas_equalTo(kWFit(41));
        }
        make.right.mas_equalTo(@-16);
    }];
    
    
    self.codeTF = [[UITextField alloc]init];
    self.codeTF.keyboardType = UIKeyboardTypeDefault;
    NSMutableAttributedString *pStr = [[NSMutableAttributedString alloc]initWithString:@"请输入6位验证码"];
    [pStr addAttribute:NSForegroundColorAttributeName value:UIColorHex(0xCCCCCC) range:NSMakeRange(0,pStr.length)];
    if(self.currentAvailableWidth < 375){
        [pStr addAttribute:NSFontAttributeName value:JPUIFontPingFangSCRegular(10) range:NSMakeRange(0,pStr.length)];
    }else{
        [pStr addAttribute:NSFontAttributeName value:JPUIFontPingFangSCRegular(14) range:NSMakeRange(0,pStr.length)];
    }
    self.codeTF.attributedPlaceholder = pStr;
    CGFloat rr_h = kWFit(51);
    if(isIPAD){
        rr_h = 51;
    }
    CGFloat c_w = [self getStringWidthWithText:@"获取验证码" font:JPUIFontPingFangSCMedium(14) viewHeight:rr_h];
    UIView *rightView = [[UIView alloc]initWithFrame:CGRectMake(0,0,c_w+22,rr_h)];
    self.countDownBtn = [[CountDownBtn alloc]initWithFrame:CGRectMake(10,0,c_w+12,rr_h)];
    [self.countDownBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [self.countDownBtn setTitleColor:KThemeColor forState:UIControlStateNormal];
    self.countDownBtn.titleLabel.font = JPUIFontPingFangSCMedium(14);
    self.countDownBtn.delegate = self;
    [self.countDownBtn addTarget:self action:@selector(countDownClick) forControlEvents:UIControlEventTouchUpInside];
    [rightView addSubview:self.countDownBtn];
    self.codeTF.rightView = rightView;
    self.codeTF.rightViewMode = UITextFieldViewModeAlways;
    self.codeTF.delegate = self;
    self.codeTF.tintColor = KThemeColor;
    [bgView addSubview:self.codeTF];
    [self.codeTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@103);
        make.right.mas_equalTo(@-10);
        if(isIPAD){
            make.bottom.mas_equalTo(-5);
        }else{
            make.bottom.mas_equalTo(-kWFit(5));
        }
        make.height.mas_equalTo(rr_h);
    }];
    if (!self.countDown) {
        self.countDown = [[YMCountDown alloc] init];
        self.countDown.delegate = self;
    }
    
    __weak typeof(self)self_weak_ = self;
    UILabel *titleLabel2 = [[UILabel alloc]init];
    titleLabel2.font = JPUIFontPingFangSCMedium(15);
    titleLabel2.textColor = KFontBlackColor;
    titleLabel2.text = @"短信验证码";
    [bgView addSubview:titleLabel2];
    [titleLabel2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@16);
        make.centerY.mas_equalTo(self_weak_.codeTF);
        make.right.mas_equalTo(@-16);
        make.height.mas_equalTo(@21);
    }];
    
    
    UIButton *sureBtn = [[UIButton alloc]init];
    [sureBtn setTitle:@"确定注销" forState:UIControlStateNormal];
    [sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    sureBtn.titleLabel.font = JPUIFontPingFangSCMedium(14);
    sureBtn.backgroundColor = KThemeColor;
    if(isIPAD){
        sureBtn.layer.cornerRadius = 49/2.0;
    }else{
        sureBtn.layer.cornerRadius = kWFit(49)/2.0;
    }
    sureBtn.layer.masksToBounds = YES;
    [sureBtn addTarget:self action:@selector(sureBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sureBtn];
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@16);
        make.right.mas_equalTo(@-16);
        if(isIPAD){
            make.top.mas_equalTo(bgView.mas_bottom).offset(20);
            make.height.mas_equalTo(@49);
        }else{
            make.top.mas_equalTo(bgView.mas_bottom).offset(kWFit(20));
            make.height.mas_equalTo(kWFit(49));
        }
    }];
    
}

#pragma mark - 屏幕宽度改变
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
    if(isIPAD){
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
           // 获取当前可用宽度并更新布局
           self.currentAvailableWidth = [DeviceUtils currentAvailableWidth];
           self.currentAvailableHeight = [DeviceUtils currentAvailableHeight];
           self.customNavigationBar.frame = CGRectMake(0, 0, self.currentAvailableWidth,kYM_NAVIGATIONBAR_HEIGHT);
           
        });
    }
}

#pragma mark - 确定注销
-(void)sureBtnClick{
    
    if(self.codeTF.text.length == 0){
        [JPProgressHUD showMsg:@"请输入验证码"];
        return;
    }
    
    NSString *phone = [[NSUserDefaults standardUserDefaults]objectForKey:@"phone"];
    self.deleteUserManager.phone = phone;
    self.deleteUserManager.mobileCode = self.codeTF.text;
    [self.deleteUserManager loadData];
    
}


-(NSString*)hideMiddleDigits:(NSString*)phoneNumber{
     NSString *maskedNumber = phoneNumber;
     if (phoneNumber.length == 13||phoneNumber.length == 11) {
         // 中国手机号码 86+11位
         // 台湾手机号码 886 +10 位
         // 香港、澳门手机号码 852+8位 853+8位
         // 日本手机号码 81+11位
         NSRange range = NSMakeRange(5,4);
         maskedNumber = [phoneNumber stringByReplacingCharactersInRange:range withString:@"****"];
     }else if (phoneNumber.length == 12) {
         // 香港手机号码 852+9位
         NSRange range = NSMakeRange(6,4);
         maskedNumber = [phoneNumber stringByReplacingCharactersInRange:range withString:@"****"];
     }
     return maskedNumber;
}


#pragma mark - 获取验证码
-(void)countDownClick{
    NSString *phone = [[NSUserDefaults standardUserDefaults]objectForKey:@"phone"];
    if(phone){
        self.sendCodeManager.mobile = phone;
        [self.sendCodeManager loadData];
    }
}

-(void)BtnClick:(UIButton *)btn{
    [self countDownClick];
}

#pragma mark - 倒计时代理 JPCountryCodeChoiceControllerDelegate
- (void)countDownWillFire:(YMCountDown *)countDown{
    self.countDownBtn.userInteractionEnabled = NO;
}

-(void)countDown:(YMCountDown *)countDown runningTime:(NSTimeInterval)runningTime{
    NSString *str = [NSString stringWithFormat:@"%is",(int)runningTime];
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [self.countDownBtn setTitle:str forState:UIControlStateNormal];
    }];

}

-(void)countDown:(YMCountDown *)countDown didStopInTime:(NSTimeInterval)time{
     self.countDownBtn.userInteractionEnabled = YES;
    [self.countDownBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
}

#pragma mark - JPAPIManagerCallBackDelegate
-(void)managerCallDLDLAPIDidSuccess:(JPAPIBaseManager *)manager{
    
    if([manager isEqual:self.sendCodeManager]){
        NSDictionary *dic = manager.response.content;
        if(dic[@"message"]){
            [JPProgressHUD showMsg:dic[@"message"]];
        }
        [self.countDown fire];
    }
    
    if([manager isEqual:self.deleteUserManager]){
        NSDictionary *dic = manager.response.content;
        if(dic[@"message"]){
            [JPProgressHUD showMsg:dic[@"message"]];
        }
        [[NSNotificationCenter defaultCenter]postNotificationName:@"deleteUserSuccess" object:nil];
        [self.navigationController popToRootViewControllerAnimated:YES];
    }
    
}

-(void)managerCallDLDLAPIDidFailed:(JPAPIBaseManager *)manager{
    if(manager.errorMessage){
        [JPProgressHUD showMsg:manager.errorMessage];
    }
}



@end
